<template>
    <div class="configuredRule">
        <el-card shadow="hover" class="card-search">
            <el-row>
                <el-col :span="20">
                    <div class="search_detail">
                        <div class="search">
                            <span class="span_name">用户名称：</span>
                            <el-input v-model="state.params.realName" placeholder="请输入" clearable />
                        </div>
                        <div class="search">
                            <span class="span_name">角色类型：</span>
                            <el-select v-model="state.params.roleId" placeholder="请选择">
                                <el-option v-for="item in state.options" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </div>
                    </div>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" :icon="Search" @click="search">搜索</el-button>
                    <el-button type="danger" :icon="Delete" @click="reast">重置</el-button>
                </el-col>
            </el-row>
        </el-card>
        <el-card shadow="hover" class="card-main">
            <el-button type="primary" :icon="CirclePlusFilled" @click="addmore">新增</el-button>
            <el-table :data="state.tableData" stripe style="width: 100%">
                <el-table-column type="index" width="55" label="序号" align="center" />
                <el-table-column prop="username" label="用户名" align="center" />
                <el-table-column prop="realName" label="姓名" align="center" />
                <el-table-column prop="mobile" label="手机号" show-overflow-tooltip align="center" />
                <el-table-column prop="roleName" label="角色类型" show-overflow-tooltip align="center" />
                <el-table-column prop="status" label="启用" show-overflow-tooltip align="center">
                    <template #default="scope">
                        <el-switch :value="scope.row.status === 1 ? true : false" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" @click="update(scope.row)">编辑</el-button>
                        <el-button type="danger" @click="Deletet(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination background @current-change="changepage" layout="prev, pager, next"
                    :total="state.totalPage" />
            </div>
        </el-card>
        <el-dialog :close-on-click-modal="false" v-model="state.dialogVisible" title="角色管理" width="30%"
            :before-close="handleClose">
            <div class="inputa">
                <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
                    :size="formSize" status-icon>
                    <el-form-item label="用户名称：" prop="username">
                        <el-input v-model="ruleForm.username" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="姓名：" prop="realName">
                        <el-input v-model="ruleForm.realName" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="手机号：" prop="mobile">
                        <el-input v-model="ruleForm.mobile" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="密码：" prop="password">
                        <el-input v-model="ruleForm.password" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="角色类型" prop="region">
                        <el-select v-model="ruleForm.region" placeholder="请选择">
                            <el-option v-for="item in state.options" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="是否启用：" prop="sation">
                        <el-switch v-model="ruleForm.sation" />
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="resetForm()">取消</el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef)"> 确定 </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
  
<script setup>
import { ref, reactive, getCurrentInstance } from 'vue'
import { Delete, Search, CirclePlusFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
const { proxy } = getCurrentInstance();
const ruleFormRef = ref()
const state = reactive({
    dialogVisible: false,
    options: [],
    name: '',
    time: '',
    tableData: [],
    page: 1,
    totalPage: 0,
    row: {},
    params: {
        monthStatus: '',
        realName: '',
        roleId: '',
        time: ['', ''],
        startDate: '',
        endDate: '',
    }
})

const formSize = ref('default')
const ruleForm = reactive({
    username: '',
    realName: '',
    mobile: '',
    password: '',
    region: '',
    sation: true,
    status: 1,
    roleIdList: [],
})

const rules = reactive({
    username: [
        { required: true, message: '不能为空', trigger: 'blur' },
    ],
    realName: [
        { required: true, message: '不能为空', trigger: 'blur' },
    ],
    mobile: [
        { required: true, message: '不能为空', trigger: 'blur' },
    ],
    // password: [
    //     { required: true, message: '不能为空', trigger: 'blur' },
    // ],
    sation: {
        required: true,
        message: '请选择',
        trigger: 'change',
    },
    region: [
        {
            required: true,
            message: '不能为空',
            trigger: 'change',
        },
    ],
    count: [
        {
            required: true,
            message: 'Please select Activity count',
            trigger: 'change',
        },
    ],
})

const changepage = (e) => {
    state.page = e
    getData()
}


const getData = async () => {
    let res = await proxy.$api.home.userPage(
        {
            limit: 10,
            page: state.page,
            username: state.params.realName,
            roleId: state.params.roleId,
        })
    state.tableData = res.data.list
    state.totalPage = res.data.total
    console.log('res', res);
}
getData(state.page)
const getSelect = async () => {
    let res = await proxy.$api.home.roleList()
    state.options = res.data
}
getSelect()
const search = () => {
    console.log('state', state.params);
    state.params.startDate = state.params.time[0]
    state.params.endDate = state.params.time[1]
    getData(state.page)
}
const reast = () => {
    state.params = {
        monthStatus: '',
        realName: '',
        time: ['', ''],
        startDate: '',
        endDate: '',
    }
    getData(state.page)
}
const update = (row) => {
    state.dialogVisible = true
    proxy.$api.home.userDetail(row.id).then(res => {
        console.log('res', res);
        ruleForm.username = res.data.username
        ruleForm.realName = res.data.realName
        ruleForm.mobile = res.data.mobile
        ruleForm.id = res.data.id
        ruleForm.password = res.data.password
        ruleForm.region = res.data.roleIdList[0]
        res.data.status === 1 ? ruleForm.sation = true : ruleForm.sation = false
    })
    state.row = row
}

const addmore = () => {
    state.dialogVisible = true
}

const Deletet = async (row) => {
    ElMessageBox.confirm('是否此角色？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'mis-msg-prompt'
    })
        .then(() => {
            proxy.$api.home.userDelet([row.id]).then(() => {
                ElMessage.success('删除成功!')
                getData()
            })
        })
        .catch(() => { })
}


const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!',ruleForm)
            ruleForm.roleIdList[0] = ruleForm.region
            ruleForm.sation === true ? ruleForm.status = 1 : ruleForm.status = 0
            console.log('ruleForm.id !=', ruleForm.id !='');
            if (ruleForm.id) {
                proxy.$api.home.userput(ruleForm).then(res => {
                    console.log('res', res)
                    if (res.msg === 'success') {
                        ElMessage.success('修改成功!')
                        state.dialogVisible = false
                        resetForm()
                        getData()
                    }
                })
            } else {
                proxy.$api.home.userSave(ruleForm).then(res => {
                    console.log('res', res)
                    if (res.msg === 'success') {
                        ElMessage.success('添加成功!')
                        state.dialogVisible = false
                        resetForm()
                        getData()
                    }
                })
            }

        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = () => {
    if (!ruleFormRef.value) return
    ruleFormRef.value.resetFields()
    setTimeout(() => {
        state.dialogVisible = false
    }, 200);
}
</script>
  
<style lang="scss" scoped>
.configuredRule {
    padding: 20px;

    .search_detail {
        display: flex;

        .search {
            margin-right: 10px;
            display: flex;
            align-items: center;

            .span_name {
                width: 110px;
                font-size: 16px;
            }
        }
    }

    .card-main {
        margin-top: 20px;
        height: calc(100vh - 200px);
        position: relative;

        .pagination {
            margin-top: 10px;
            display: flex;
            justify-content: flex-end;
            text-align: right;
        }
    }
}
</style>